package geektime.io.netty.homework;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * 模拟客户端
 */
public class DemoClient {
    private static final String HOST = System.getProperty("host", "localhost");
    private static final int PORT = Integer.valueOf(System.getProperty("port", "12345"));

    public static void main(String[] args) {
        // 创建客户端的事件组
        NioEventLoopGroup worker = new NioEventLoopGroup();
        // 创建客户端启动的Bootstrap
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 设置bootStrap相关参数，包含事件组、IO通道类型、通道配置选项和handler
            bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new DemoClientHandler());
                    }
                });
            System.out.println("Client start...");
            // 连接ip和端口
            ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync();
            // 自我阻塞直到通道关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
